<script setup>
import { ref } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
import { 
    EllipsisHorizontalIcon,
    MagnifyingGlassIcon,
    PlusIcon,
    PencilIcon,
    TrashIcon,
    FolderIcon,
    DocumentTextIcon
} from '@heroicons/vue/24/outline'
import debounce from 'lodash/debounce'
import Pagination from '@/Components/UI/Pagination.vue'
import ConfirmDialog from '@/Components/UI/ConfirmDialog.vue'
import { useToast } from '@/Composables/useToast'

const props = defineProps({
    categories: {
        type: Object,
        required: true
    },
    filters: {
        type: Object,
        default: () => ({})
    }
})

const toast = useToast()
const search = ref(props.filters.search || '')

// 删除确认
const showDeleteConfirm = ref(false)
const categoryToDelete = ref(null)

// 处理搜索
const handleSearch = debounce(() => {
    router.get(route('admin.categories.index'), {
        search: search.value
    }, {
        preserveState: true,
        preserveScroll: true
    })
}, 300)

// 删除分类
const confirmDelete = (category) => {
    categoryToDelete.value = category
    showDeleteConfirm.value = true
}

const cancelDelete = () => {
    showDeleteConfirm.value = false
    categoryToDelete.value = null
}

const deleteCategory = () => {
    if (!categoryToDelete.value) return
    
    router.delete(route('admin.categories.destroy', categoryToDelete.value.id), {
        onSuccess: () => {
            toast.success('分类删除成功')
            showDeleteConfirm.value = false
            categoryToDelete.value = null
        },
        onError: (errors) => {
            console.error('删除失败：', errors)
            const errorMessage = errors?.error || errors?.message || '删除失败，请重试'
            toast.error(errorMessage)
            if (errorMessage.includes('权限') || errorMessage.includes('无权')) {
                showDeleteConfirm.value = false
                categoryToDelete.value = null
            }
        }
    })
}
</script>

<template>
    <AdminLayout>
        <Head title="分类管理" />

        <div class="space-y-6">
            <!-- 页面标题和操作 -->
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">分类管理</h1>
                    <p class="mt-2 text-sm text-gray-600">
                        共 {{ categories.meta?.total || 0 }} 个分类
                    </p>
                </div>
                <Link
                    :href="route('admin.categories.create')"
                    class="inline-flex items-center gap-x-2 rounded-md bg-orange-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-orange-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 transition-colors"
                >
                    <PlusIcon class="h-5 w-5" />
                    新建分类
                </Link>
            </div>

            <!-- 搜索栏 -->
            <div class="flex flex-col sm:flex-row gap-4">
                <div class="flex-1">
                    <div class="relative">
                        <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                            <MagnifyingGlassIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                        </div>
                        <input
                            type="search"
                            v-model="search"
                            placeholder="搜索分类名称或描述..."
                            class="block w-full rounded-md border border-gray-300 bg-white py-2 pl-10 pr-3 text-sm placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                            @input="handleSearch"
                        >
                    </div>
                </div>
            </div>

            <!-- 分类列表表格 -->
            <div class="overflow-hidden bg-white rounded-lg border border-gray-200 shadow-sm">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">
                                    分类
                                </th>
                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                    Slug
                                </th>
                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                    描述
                                </th>
                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                                    文章数
                                </th>
                                <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
                                    <span class="sr-only">操作</span>
                                </th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 bg-white">
                            <tr 
                                v-for="category in categories.data" 
                                :key="category.id" 
                                class="hover:bg-gray-50 transition-colors"
                            >
                                <td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm sm:pl-6">
                                    <div class="flex items-center gap-x-3">
                                        <div class="h-10 w-10 flex-shrink-0">
                                            <div class="h-10 w-10 rounded-lg bg-orange-100 flex items-center justify-center">
                                                <FolderIcon class="h-6 w-6 text-orange-600" />
                                            </div>
                                        </div>
                                        <div class="min-w-0 flex-1">
                                            <div class="font-medium text-gray-900">
                                                {{ category.name }}
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    <code class="text-xs bg-gray-100 px-2 py-1 rounded">{{ category.slug }}</code>
                                </td>
                                <td class="px-3 py-4 text-sm text-gray-500">
                                    <div class="max-w-xs truncate">
                                        {{ category.description || '无描述' }}
                                    </div>
                                </td>
                                <td class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                    <div class="flex items-center gap-x-1">
                                        <DocumentTextIcon class="h-4 w-4 text-gray-400" />
                                        {{ category.posts_count || 0 }}
                                    </div>
                                </td>
                                <td class="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                                    <Menu as="div" class="relative inline-block text-left">
                                        <MenuButton class="inline-flex items-center rounded-full p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 focus:outline-none">
                                            <span class="sr-only">打开选项</span>
                                            <EllipsisHorizontalIcon class="h-5 w-5" />
                                        </MenuButton>
                                        <transition
                                            enter-active-class="transition ease-out duration-100"
                                            enter-from-class="transform opacity-0 scale-95"
                                            enter-to-class="transform opacity-100 scale-100"
                                            leave-active-class="transition ease-in duration-75"
                                            leave-from-class="transform opacity-100 scale-100"
                                            leave-to-class="transform opacity-0 scale-95"
                                        >
                                            <MenuItems class="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                                                <div class="py-1">
                                                    <MenuItem v-slot="{ active }">
                                                        <Link
                                                            :href="route('admin.categories.edit', category.id)"
                                                            :class="[
                                                                active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
                                                                'group flex items-center gap-x-2 px-4 py-2 text-sm'
                                                            ]"
                                                        >
                                                            <PencilIcon class="h-4 w-4" />
                                                            编辑
                                                        </Link>
                                                    </MenuItem>
                                                    <MenuItem v-slot="{ active }">
                                                        <button
                                                            @click="confirmDelete(category)"
                                                            :class="[
                                                                active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
                                                                'group flex w-full items-center gap-x-2 px-4 py-2 text-left text-sm'
                                                            ]"
                                                        >
                                                            <TrashIcon class="h-4 w-4" />
                                                            删除
                                                        </button>
                                                    </MenuItem>
                                                </div>
                                            </MenuItems>
                                        </transition>
                                    </Menu>
                                </td>
                            </tr>
                            <tr v-if="categories.data.length === 0">
                                <td colspan="5" class="px-6 py-12 text-center text-sm text-gray-500">
                                    <FolderIcon class="mx-auto h-12 w-12 text-gray-400" />
                                    <h3 class="mt-2 font-medium text-gray-900">没有分类</h3>
                                    <p class="mt-1 text-gray-500">开始创建您的第一个分类吧。</p>
                                    <div class="mt-6">
                                        <Link
                                            :href="route('admin.categories.create')"
                                            class="inline-flex items-center gap-x-2 rounded-md bg-orange-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-orange-500"
                                        >
                                            <PlusIcon class="h-5 w-5" />
                                            新建分类
                                        </Link>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 分页 -->
            <div v-if="categories.meta && categories.meta.last_page > 1">
                <Pagination :links="categories.meta.links || []" />
            </div>
        </div>

        <!-- 删除确认对话框 -->
        <ConfirmDialog
            :show="showDeleteConfirm"
            title="删除分类"
            content="确定要删除这个分类吗？此操作不可恢复。"
            confirm-text="删除"
            cancel-text="取消"
            @confirm="deleteCategory"
            @close="cancelDelete"
        />
    </AdminLayout>
</template> 